const sharp = require("sharp");
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const ora = require("ora");
const imageMinify = (inputDir, outDir) => {
  let outputDir = outDir ?? path.join(inputDir, "./minify");
  fs.readdir(inputDir, (err, files) => {
    if (err) {
      console.error("Error reading input directory:", err);
      return;
    }

    fs.access(outputDir, fs.constants.F_OK, (err) => {
      if (err) {
        fs.mkdirSync(outputDir);
        return;
      }
    });
    const fileExtern = [
      "avif",
      "dz",
      "fits",
      "gif",
      "heif",
      "input",
      "jpeg",
      "jpg",
      "jp2",
      "jxl",
      "magick",
      "openslide",
      "pdf",
      "png",
      "ppm",
      "raw",
      "svg",
      "tiff",
      "tif",
      "v",
      "webp",
    ];
    const fileList = files.filter((item) => {
      const extern = path.extname(item).slice(1)?.toLowerCase();
      return fileExtern.includes(extern);
    });
    if (fileList.length > 0) {
      const spinner = ora(`开始处理${fileList.length}个文件`);
      let count = 0;
      fileList.forEach((file) => {
        const extern = path.extname(file).slice(1)?.toLowerCase();
        const inputFile = path.join(inputDir, file);
        const outputFile = path.join(outputDir, file);
        const size = fs.statSync(inputFile).size;
        sharp(inputFile)
          .toFormat(extern, { quality: 80 })
          .toFile(outputFile, (err, info) => {
            console.log("lfsz", info);

            if (err) {
              console.log(chalk.red("错误信息：", err));
              count++;
            } else {
              count++;
              console.log(
                chalk.green(
                  `转换成功(${count}/${fileList.length})：`,
                  size,
                  file
                )
              );
              if (count === fileList.length) {
                spinner.succeed(`处理完成，处理后的文件在：${outputDir}`);
              }
            }
          });
      });
    } else {
      console.log(chalk.yellow("无可处理的文件，请检查文件后缀"));
    }
  });
};
module.exports = {
  imageMinify,
};
